import {
	getInfo,
	login
} from "../api/byfz";
import {
	config
} from "../config/config";
import store from "../store";
import PlaneInfo from "./planeInfoStorage";
export const PLANE_STATUS = {
	STAGING: 0,
	FORMALLY_EFFECTIVE: 1,
	FINISH: 2,
	CANCEL: 3,
	TIME_OUT: 4,
	GUI_DAN: 5
}

export function checkLogin() {
	if (!uni.getStorageSync('token')) {
		setTimeout(() => {
			uni.showToast({
				icon: 'none',
				title: '请先登录!',
				duration: 1000
			})
		}, 500)
		uni.navigateTo({
			url: '/pages/login/login'
		})
		return false;
	}
	return true;
}

export const promisic = function(func) {
	return function(params = {}) {
		return new Promise((resolve, reject) => {
			const args = Object.assign(params, {
				success: (res) => {
					resolve(res)
				},
				fail: (error) => {
					reject(error);
				}
			});
			func(args);
		});
	};
};
//遇到401 重新登录刷新token
export async function autoLogin() {
	uni.setStorageSync('loginInfo', {
		phone: '18822334455',
		password: '123456'
	})
	if (uni.getStorageSync('loginInfo')) {
		const {
			phone,
			password
		} = uni.getStorageSync('loginInfo');
		try {
			await loginMethod({
				phone,
				password,
				autoLogin: true
			})
		} catch (e) {
			clearLoginState()
		}
	}
}
//登录
export async function loginMethod({
	phone,
	password,
	autoLogin = false
}) {
	const res = await login({
		username: phone,
		password: password
	})
	console.log("res==", res);
	if (res.token) {
		uni.setStorageSync('token', res.token)
		uni.setStorageSync('userId', res.userId)
	}
	uni.showToast({
		icon: 'success',
		title: '登录成功!'
	})
	const userInfoRes = await getInfo();
	let userInfo = userInfoRes.data
	uni.setStorageSync('isIdentity', userInfo.identity == 1 ? true : false)
	userInfo.userId = res.userId;
	store.dispatch("user/updateUserInfo", userInfo);
	if (!autoLogin) {
		uni.setStorageSync("loginInfo", {
			phone,
			password
		})
		if (userInfo.isResetPwd == 0) {
			uni.navigateTo({
				url: '../my/changePasswordFirst'
			})
			setTimeout(() => {
				uni.showToast({
					title: '请先修改密码!',
					icon: false
				})
			}, 200)
		} else {
			uni.switchTab({
				url: '../index/index'
			})
		}
	}
}

export function clearLoginState() {
	store.dispatch("user/updateUserInfo", {});
	uni.clearStorageSync()
	PlaneInfo.clearPlaneInfo()
}


export async function initUserInfo(isClearLoginInfo = false) {
	const userInfoRes = await getInfo();
	if(!userInfoRes){
		return;
	}
	let userInfo = userInfoRes.data
	userInfo.userId = uni.getStorageSync('userId')
	uni.setStorageSync('isIdentity', userInfo.identity == 1 ? true : false)
	store.dispatch("user/updateUserInfo", userInfo);
	PlaneInfo.initPlaneInfo()
	if (userInfo.isResetPwd == 0) {
		if (isClearLoginInfo) {
			clearLoginState()
		} else {
			uni.navigateTo({
				url: '/pages/my/changePasswordFirst'
			})
		}

	}
}


export function renderTime() {
	const endAt = store.state.user.planeInfo.endAt
	if (endAt && endAt.split(' ').length == 2) {
		let dateStr = endAt.split(' ')[0];
		let dateStr2 = endAt.split(' ')[1] === '12:00:00' ? '上午' : endAt.split(' ')[1] === '17:00:00' ? '下午' : ''
		return dateStr + dateStr2
	} else {
		return ''
	}
}

export function getMessionId() {
	if (uni.getStorageSync('searchDetail')) {
		return uni.getStorageSync('searchDetail').id
	}
	return store.state.user.planeInfo.projectId ? store.state.user.planeInfo
		.projectId : '9999'
}


export function preView(url, type = 'image', name) {
	if (type === 'image') {
		uni.previewImage({
			current: url, //当前预览图片url
			urls: [url],
			fail: (e) => {
				uni.showToast({
					title: '图片打开失败!',
					icon: 'error'
				});
			}
		})
	} else {
		uni.showLoading({
			mask: true
		})
		uni.downloadFile({
			url: url,
			// filePath: wx.env.USER_DATA_PATH  +'/'+ name,//下载到自定义的文件夹里并命名,这里是一个临时的文件地址，name是你的文件名，.pdf 是文件保存的类型，这里我保存为PDF格式
			success: res => {
				console.log('url', res);
				if (res.statusCode === 200) {
					// 预览pdf文件
					uni.openDocument({
						filePath: res.tempFilePath,
						showMenu: true, // 右上角菜单，可以进行分享保存pdf
						success: function(file) {
							console.log('file-success', file);
						},
						fail: (e) => {
							console.log("e==", e);
							uni.showToast({
								title: '文件打开失败!',
								icon: 'error'
							});
						}
					});
				} else {
					uni.hideLoading();
					uni.showToast({
						title: '文件加载失败',
						icon: 'error'
					});
				}
			},
			fail: (e) => {
				uni.showToast({
					title: '文件打下载失败',
					icon: 'error'
				});
				uni.hideLoading()
			}
		});
	}

}

export function makeData(item) {
	if (item.endAt && item.endAt.split(' ').length == 2) {
		let afterText = item.endAt.split(' ')[1] === '12:00:00' ? '上午' : '下午'
		item.tiemText = item.endAt.split(' ')[0] + afterText
	}
	if (item.teamNumberText) {
		let teamNumberTextList = [];
		item.teamNumberText.split(',').forEach((item) => {
			teamNumberTextList.push({
				name: item
			})
		})
		item.teamNumberTextList = teamNumberTextList;
	}
	if (item.filePath) {
		let list = [];
		for (let item of item.filePath.split(',')) {
			list.push({
				name: item.split('/')[item.split('/').length - 1].split('.')[0],
				type: item.split('/')[item.split('/').length - 1].split('.')[1],
				path: item
			})
		}
		item.filePathList = list
	}
	item.isMeCreateBy = item.createBy == uni.getStorageSync('userId') ? true : false
	return item
}
